<script lang="ts" setup>
import useModal from '@/hooks/useModal'
import { get, post, message, loadFile, checkBtnPermission } from '@/utils'
import { FormInstance, TableColumnData } from '@arco-design/web-vue'
import { BtnPermission } from '@/enum/permission'
import isEmpty from 'lodash/isEmpty'
import useOptions from '@/hooks/useOptions'
import useQQMap from '@/hooks/useQQMap'
const formRef = ref() as Ref<FormInstance>
const props = defineProps<{ info: any }>()
const emit = defineEmits(['getInfo'])
const { jsonp, mapKey, map, initMap, locationService, _window } = useQQMap(undefined, { zoom: 11 })
const detail = reactive({
  isOpenDelivery: 0,
  sellerDeliveryConfig: {
    addressId: 0,
    advanceType: 0,
    advanceUnit: 0,
    advanceValue: 0,
    deliveryPrice: 0,
    deliveryScope: 0,
    isOpenAuto: 0,
    isOpenTiming: 0,
    minPrice: 0,
    openId: '',
    shopId: '',
    timeList: [] as any[],
  },
  lat: '',
  lng: '',
})

const submit = () => {
  formRef.value.validate(err => {
    if (!err) {
      if (!checkBtnPermission(BtnPermission.编辑)) return false
      const query = Object.assign({}, detail)
      post({ url: '/server-shop/sys-seller/seller/update/delivery', data: query }, ({ code, msg }) => {
        message({
          type: code == 200 ? 'success' : 'error',
          content: msg,
        })
        if (code == 200) {
        }
      })
    }
  })
}
const { options } = useOptions({
  api: '/server-shop/sys-seller/seller/address/list',
})
watch(
  () => props.info,
  n => {
    if (!isEmpty(n)) {
      Object.assign(detail, n)
      if (detail.isOpenDelivery == 1) {
        init()
      }
    }
  },
  { deep: true }
)
onMounted(() => {
  if (!isEmpty(props.info)) {
    Object.assign(detail, props.info)
    if (isEmpty(detail.sellerDeliveryConfig)) {
      detail.sellerDeliveryConfig = {
        addressId: 0,
        advanceType: 0,
        advanceUnit: 0,
        advanceValue: 0,
        deliveryPrice: 0,
        deliveryScope: 0,
        isOpenAuto: 0,
        isOpenTiming: 0,
        minPrice: 0,
        openId: '',
        shopId: '',
        timeList: [] as any[],
      }
    }
    if (detail.isOpenDelivery == 1) {
      init()
    }
  }
})
watch(
  () => detail.isOpenDelivery,
  n => {
    if (n == 1) {
      init()
    }
  }
)
const init = () => {
  nextTick(() => {
    initMap(document.getElementById('map') as HTMLElement, () => {
      const { lat = 10, lng = 10 } = currentAddress.value
      map.value.setCenter(new _window.qq.maps.LatLng(lat, lng))
      setCircle()
    })
  })
}

/**
 * 设置范围圈
 */
const setCircle = () => {
  const { Circle, LatLng, Color } = _window.qq.maps
  const { lat, lng } = currentAddress.value
  const options = {
    map: map.value,
    center: new LatLng(lat, lng),
    /**地图接收的单位是米，转换一次 */
    radius: detail.sellerDeliveryConfig.deliveryScope * 1000,
    fillColor: new Color(0, 15, 255, 0.5),
    strokeWeight: 2,
    strokeColor: '#333',
  }
  console.log(options)

  var circle = new Circle(options)
  circle.setMap(map.value)
}
watch(
  () => detail.sellerDeliveryConfig.deliveryScope,
  n => {
    if (detail.isOpenDelivery == 1) {
      nextTick(() => {
        setCircle()
      })
    }
  }
)
const timeStore = reactive({
  addFn: () => {
    detail.sellerDeliveryConfig.timeList.push({
      beginTime: '',
      endTime: '',
      status: '',
    })
  },
  onChange: (item, index) => {
    const [beginTime, endTime] = item
    // detail.sellerDeliveryConfig.timeList[index].status = isValidEndTime(beginTime, endTime) ? '' : 'error'
    detail.sellerDeliveryConfig.timeList[index].beginTime = beginTime
    detail.sellerDeliveryConfig.timeList[index].endTime = endTime
  },
})
const isValidEndTime = (startTime, endTime) => {
  // 解析时间字符串为分钟数
  function parseTimeToMinutes(time) {
    const [hours, minutes] = time.split(':').map(Number)
    return hours * 60 + minutes // 将时间转换为分钟数
  }

  const startMinutes = parseTimeToMinutes(startTime)
  const endMinutes = parseTimeToMinutes(endTime)

  // 如果结束时间大于开始时间，或者结束时间跨日（小于开始时间但加上24小时后大于开始时间）
  return endMinutes > startMinutes || endMinutes + 24 * 60 > startMinutes
}
/**当前选中的地址 */
const currentAddress = computed(() => options.value.filter(f => f.id == detail.sellerDeliveryConfig.addressId)?.[0] || { lat: 10, lng: 10 })

watch(
  () => detail.sellerDeliveryConfig.addressId,
  n => {
    init()
  }
)
</script>
<template>
  <div class="distribution">
    <a-form :model="detail" ref="formRef" @submit="submit" :label-col-props="{ span: 3 }" :wrapper-col-props="{ span: 21 }">
      <a-form-item field="isOpenDelivery" label="配送设置">
        <a-switch v-model="detail.isOpenDelivery" :checked-value="1" :unchecked-value="0" placeholder="请选择">
          <template #checked> 开启 </template>
          <template #unchecked> 关闭 </template>
        </a-switch>
      </a-form-item>
      <template v-if="detail.isOpenDelivery == 1">
        <a-form-item field="sellerDeliveryConfig.addressId" label="选择地址" :rules="[{ required: true, message: '请选择地址' }]" :validate-trigger="['change', 'blur']">
          <a-select :options="options" v-model="detail.sellerDeliveryConfig.addressId" />
        </a-form-item>
        <a-form-item label="配送范围">
          <div class="content">
            <a-space direction="vertical">
              <a-input-number v-model="detail.sellerDeliveryConfig.deliveryScope" style="width: 200px">
                <template #append>公里</template>
              </a-input-number>
              <div id="map"></div>
            </a-space>
          </div>
        </a-form-item>

        <a-form-item label="配送价格">
          <div class="content">
            <a-form-item label="起送价" :rules="[{ required: true, message: '请输入起送价' }]" :validate-trigger="['change', 'blur']" field="sellerDeliveryConfig.minPrice">
              <a-input-number v-model="detail.sellerDeliveryConfig.minPrice" placeholder="请输入" style="width: 200px">
                <template #append> 元 </template>
              </a-input-number>
            </a-form-item>
            <a-form-item label="基础运费" :rules="[{ required: true, message: '请输入基础运费' }]" :validate-trigger="['change', 'blur']" field="sellerDeliveryConfig.deliveryPrice">
              <a-input-number v-model="detail.sellerDeliveryConfig.deliveryPrice" placeholder="请输入" style="width: 200px">
                <template #append> 元 </template>
              </a-input-number>
            </a-form-item>
          </div>
        </a-form-item>
        <a-form-item label="自动配送">
          <a-switch v-model="detail.sellerDeliveryConfig.isOpenAuto" :checked-value="1" :unchecked-value="0" placeholder="请选择">
            <template #checked> 开启 </template>
            <template #unchecked> 关闭 </template>
          </a-switch>
        </a-form-item>
        <a-form-item label="配送功能">
          <a-switch v-model="detail.sellerDeliveryConfig.isOpenTiming" :checked-value="1" :unchecked-value="0" placeholder="请选择">
            <template #checked> 开启 </template>
            <template #unchecked> 关闭 </template>
          </a-switch>
        </a-form-item>
        <a-form-item label="可选择配送时间" v-if="detail.sellerDeliveryConfig.isOpenTiming == 1">
          <div class="content">
            <a-form-item label="可配送时间">
              <div class="box">
                <a-form-item v-for="(item, index) in detail.sellerDeliveryConfig.timeList" label="" :validate-status="item.status" :label-col-props="{ span: 0 }">
                  <a-time-picker type="time-range" format="HH:mm" @change="data => timeStore.onChange(data, index)" :default-value="[item.beginTime, item.endTime]" />
                </a-form-item>
                <div>
                  <a-button type="text" @click="timeStore.addFn">添加时间段</a-button>
                </div>
              </div>
            </a-form-item>
            <a-form-item label="买家提前下单时间">
              <a-radio-group
                v-model="detail.sellerDeliveryConfig.advanceType"
                :options="[
                  { label: '无需提前', value: 1 },
                  { label: '提前', value: 2 },
                ]"
              />
            </a-form-item>
            <a-form-item label="买家下单时间" v-if="detail.sellerDeliveryConfig.advanceType == 2">
              <a-input-group>
                <a-input-number v-model="detail.sellerDeliveryConfig.advanceValue" :style="{ width: '160px' }" placeholder="请输入" />
                <a-select
                  v-model="detail.sellerDeliveryConfig.advanceUnit"
                  :options="[
                    { label: '天', value: 1 },
                    { label: '小时', value: 2 },
                    { label: '分钟', value: 3 },
                  ]"
                  :style="{ width: '160px' }"
                  placeholder="请选择"
                />
              </a-input-group>
            </a-form-item>
          </div>
        </a-form-item>
      </template>
      <a-form-item label="">
        <div style="flex: 2">
          <a-button type="primary" handle-submit html-type="submit" style="margin: auto; width: 200px">保存</a-button>
        </div>
      </a-form-item>
    </a-form>
  </div>
</template>
<style lang="less" scoped>
.distribution {
  max-width: 1200px;
  .content {
    background: rgba(245, 247, 250, 0.6);
    padding: 10px;
    flex: 2;
  }
  .box {
    background: white;
    padding: 10px;
    flex: 2;
  }
  #map {
    width: 1000px;
    height: 500px;
  }
}
</style>
